package com.power.sifa.correction.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.correction.model.Cre_record_ga;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.power.sifa.correction.model.Crc_camera;
import com.power.sifa.correction.dao.Crc_cameraDao;
import com.power.sifa.correction.service.Crc_cameraService;
import com.power.sifa.correction.model.pageInfo.Crc_cameraPageInfo;

import org.springframework.transaction.annotation.Transactional;

import java.awt.geom.Point2D;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 摄像头信息业务层实现
 */
@Service
public class Crc_cameraServiceImpl extends BaseServiceImpl implements Crc_cameraService {

    private static final Logger log = LoggerFactory.getLogger(Crc_cameraServiceImpl.class);
    @Autowired
    private Crc_cameraDao dao;

    @Override
    public Crc_camera getById(String id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Crc_camera crc_camera) {
        // save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (crc_camera.getPrimaryKey() != null) {
            Crc_camera crc_camerafDb = dao.findById(crc_camera.getPrimaryKey()).orElse(null);
            if (crc_camerafDb != null) {
                BeanUtils.copyProperties(crc_camera, crc_camerafDb);
                crc_camerafDb.setDeleted(0);
                dao.save(crc_camerafDb);
                return;
            }
        }
        crc_camera.setDeleted(0);
        dao.save(crc_camera);
    }

    @Override
    public void removeById(String id) {
        dao.removeByIds(Arrays.asList(id));
    }

    @Override
    public Page<Crc_camera> findAll(Crc_cameraPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if ("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        } else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() <= 1 ? 0 : pageInfo.getPageNumber() - 1, pageInfo.getPageSize(), sort);
        //查询条件
        pageInfo.setF_deleted(0);
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<String> ids) {
        dao.removeByIds(ids);
    }

    @Override
    public List<Crc_camera> findAll() {
        Crc_cameraPageInfo pageInfo = new Crc_cameraPageInfo();
        pageInfo.setF_deleted(0);
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec);
    }

    @Override
    public void saveAll(List<Crc_camera> list) {
        if (CollectionUtil.isNotEmpty(list)) {
            list.stream().forEach(el -> {
                el.setDeleted(0);
            });
        }
        dao.saveAll(list);
    }

    /**
     * 生成对应的摄像头数据
     *
     * @param recordList 公安推送数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateCameraInfo(List<Cre_record_ga> recordList) {
        synchronized (recordList) {
            if (CollectionUtil.isNotEmpty(recordList)) {
                recordList = recordList.stream().filter(el -> ObjectUtil.isNotNull(el.getLatcamera()) && ObjectUtil.isNotNull(el.getLngcamera())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(recordList)) {
                    // 查询全部的数据
                    List<Crc_camera> cameraList = dao.findAll();
                    Set<String> locationSet = new HashSet<>();
                    if (CollectionUtil.isNotEmpty(cameraList)) {
                        locationSet = cameraList.stream().filter(el -> ObjectUtil.isNotNull(el.getLat()) && ObjectUtil.isNotNull(el.getLng())).map(el -> el.getLat() + "_" + el.getLng()).collect(Collectors.toSet());
                    }
                    List<Crc_camera> saveCameraList = new ArrayList();
                    Set<String> finalLocationSet = locationSet;
                    recordList.stream().forEach(el -> {
                        String key = el.getLatcamera() + "_" + el.getLngcamera();
                        if (!finalLocationSet.contains(key)) {
                            Crc_camera camera = new Crc_camera();
                            camera.setId(NanoIdUtils.randomNanoId());
                            camera.setName("摄像头");
                            camera.setLat(el.getLatcamera());
                            camera.setLng(el.getLngcamera());
                            saveCameraList.add(camera);
                        }
                    });
                    if (CollectionUtil.isNotEmpty(saveCameraList)) {
                        this.saveAll(saveCameraList);
                    }
                }
            }
        }
    }

    /**
     * 查询全部摄像头的经纬度坐标
     *
     * @return
     */
    @Override
    public List<String> findAllLatlng() {
        return dao.findAllLatlng();
    }

    /**
     * 生成经纬度坐标
     *
     * @param number
     * @return
     */
    @Override
    public String getLatlng(Double number) {
        String strLanlot = "0.0000000";
        strLanlot = String.valueOf(number);
        // 获得第一个点的位置
        int index = strLanlot.indexOf(".");
        // 根据点的位置，截取 字符串。得到结果 result
        String result = strLanlot.substring(index + 1);
        if (result.length() < 7) {
            result = String.format("%-" + 7 + "s", result).replace(" ", "0");
        }
        strLanlot = strLanlot.substring(0, index + 1) + result.substring(0, 7);
        return strLanlot;
    }

    @Override
    public Integer getCameraSize() {
        Integer size = 0;
        List<Point2D.Double> range = getRange();
        List<Crc_camera> crcCameraList = dao.findCrcCameraList();
        for (Crc_camera crcCamera : crcCameraList) {
            Point2D.Double point = new Point2D.Double(crcCamera.getLng(), crcCamera.getLat());
            if (isPtInPoly(point, range)) {
                size++;
            }
        }
        return size;
    }

    /**
     * 从js文件中获取范围坐标
     *
     * @return
     */
    public static List<Point2D.Double> getRange() {
        List<Point2D.Double> pts = new ArrayList<Point2D.Double>();
        String filePath = "D:\\WorkSpace\\sifa\\dateDemo\\coordinate\\ncs.js";
        try {
            String jsonContent = new String(Files.readAllBytes(Paths.get(filePath)));
            String jsonStr = jsonContent.substring(jsonContent.indexOf("{"), jsonContent.lastIndexOf("}") + 1);
            JSONObject jsonObject = new JSONObject(jsonStr);
            JSONArray jsonArray = jsonObject.getJSONArray("ad_360100");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject point = jsonArray.getJSONObject(i);
                double lng = point.getDouble("lng");
                double lat = point.getDouble("lat");
                pts.add(new Point2D.Double(lng, lat));
            }

        } catch (IOException e) {
            log.error("读取文件异常: {}", e.getMessage());
        } catch (JSONException e) {
            log.error("json解析异常: {}", e.getMessage());
        }
        return pts;
    }

    public boolean isPtInPoly(Point2D.Double point, List<Point2D.Double> pts){
        int N = pts.size();
        boolean boundOrVertex = true; //如果点位于多边形的顶点或边上，也算做点在多边形内，直接返回true
        int intersectCount = 0;//cross points count of x
        double precision = 2e-10; //浮点类型计算时候与0比较时候的容差
        Point2D.Double p1, p2;//neighbour bound vertices
        Point2D.Double p = point; //当前点
        p1 = pts.get(0);//left vertex
        for(int i = 1; i <= N; ++i){//check all rays
            if(p.equals(p1)){
                return boundOrVertex;//p is an vertex
            }
            p2 = pts.get(i % N);//right vertex
            if(p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)){//ray is outside of our interests
                p1 = p2;
                continue;//next ray left point
            }
            if(p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)){//ray is crossing over by the algorithm (common part of)
                if(p.y <= Math.max(p1.y, p2.y)){//x is before of ray
                    if(p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)){//overlies on a horizontal ray
                        return boundOrVertex;
                    }
                    if(p1.y == p2.y){//ray is vertical
                        if(p1.y == p.y){//overlies on a vertical ray
                            return boundOrVertex;
                        }else{//before ray
                            ++intersectCount;
                        }
                    }else{//cross point on the left side
                        double xinters = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;//cross point of y
                        if(Math.abs(p.y - xinters) < precision){//overlies on a ray
                            return boundOrVertex;
                        }
                        if(p.y < xinters){//before ray
                            ++intersectCount;
                        }
                    }
                }
            }else{//special case when ray is crossing through the vertex
                if(p.x == p2.x && p.y <= p2.y){//p crossing over p2
                    Point2D.Double p3 = pts.get((i+1) % N); //next vertex
                    if(p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)){//p.x lies between p1.x & p3.x
                        ++intersectCount;
                    }else{
                        intersectCount += 2;
                    }
                }
            }
            p1 = p2;//next ray left point
        }
        if(intersectCount % 2 == 0){//偶数在多边形外
            return false;
        } else { //奇数在多边形内
            return true;
        }
    }

}
